/**
 * 未读消息管理工具类
 * 用于管理好友消息的未读状态和数量
 */

const STORAGE_KEY = 'unread_messages'; // 本地存储键

/**
 * 获取所有未读消息
 * @returns {Object} { friendPhone: unreadCount }
 */
function getAllUnread() {
  try {
    const data = wx.getStorageSync(STORAGE_KEY);
    return data || {};
  } catch (e) {
    console.error('❌ 读取未读消息失败:', e);
    return {};
  }
}

/**
 * 保存所有未读消息
 * @param {Object} unreadData 
 */
function saveAllUnread(unreadData) {
  try {
    wx.setStorageSync(STORAGE_KEY, unreadData);
  } catch (e) {
    console.error('❌ 保存未读消息失败:', e);
  }
}

/**
 * 增加未读消息数量
 * @param {String} friendPhone - 好友手机号（融云用户ID）
 * @param {Number} count - 增加的数量
 */
function addUnread(friendPhone, count = 1) {
  if (!friendPhone) return;
  
  const unreadData = getAllUnread();
  unreadData[friendPhone] = (unreadData[friendPhone] || 0) + count;
  
  saveAllUnread(unreadData);
  console.log(`📬 增加未读消息: ${friendPhone} +${count} = ${unreadData[friendPhone]}`);
  
  // 触发更新事件
  notifyUnreadChange();
}

/**
 * 清除某个好友的未读消息
 * @param {String} friendPhone - 好友手机号（融云用户ID）
 */
function clearUnread(friendPhone) {
  if (!friendPhone) return;
  
  const unreadData = getAllUnread();
  if (unreadData[friendPhone]) {
    delete unreadData[friendPhone];
    saveAllUnread(unreadData);
    console.log(`✅ 清除未读消息: ${friendPhone}`);
    
    // 触发更新事件
    notifyUnreadChange();
  }
}

/**
 * 获取某个好友的未读消息数量
 * @param {String} friendPhone - 好友手机号（融云用户ID）
 * @returns {Number}
 */
function getUnread(friendPhone) {
  if (!friendPhone) return 0;
  
  const unreadData = getAllUnread();
  return unreadData[friendPhone] || 0;
}

/**
 * 获取总未读消息数量
 * @returns {Number}
 */
function getTotalUnread() {
  const unreadData = getAllUnread();
  let total = 0;
  
  for (let phone in unreadData) {
    total += unreadData[phone];
  }
  
  return total;
}

/**
 * 清除所有未读消息
 */
function clearAllUnread() {
  saveAllUnread({});
  console.log('✅ 清除所有未读消息');
  notifyUnreadChange();
}

/**
 * 通知未读消息变化（触发页面更新）
 */
function notifyUnreadChange() {
  // 发送全局事件通知
  const pages = getCurrentPages();
  pages.forEach(page => {
    if (page.updateUnreadStatus && typeof page.updateUnreadStatus === 'function') {
      page.updateUnreadStatus();
    }
  });
}

/**
 * 初始化融云消息监听
 */
function initRongCloudListener() {
  try {
    // 获取融云实例
    const RongIMLib = getApp().globalData.RongIMLib;
    const RongIMClient = getApp().globalData.RongIMClient;
    
    if (!RongIMClient) {
      console.log('⚠️ 融云未初始化，跳过消息监听');
      return;
    }
    
    console.log('👂 初始化融云消息监听');
    
    // 监听新消息
    RongIMLib.addEventListener(RongIMLib.EventType.MESSAGES, (event) => {
      console.log('📨 收到融云消息:', event);
      
      const messages = event.messages || [];
      messages.forEach(message => {
        // 获取发送者ID（手机号）
        const senderPhone = message.senderUserId;
        
        // 只处理私聊消息
        if (message.conversationType === RongIMLib.ConversationType.PRIVATE) {
          // 增加未读数
          addUnread(senderPhone, 1);
          
          console.log(`📬 新消息来自: ${senderPhone}`);
        }
      });
    });
    
    console.log('✅ 融云消息监听初始化完成');
  } catch (e) {
    console.error('❌ 初始化融云消息监听失败:', e);
  }
}

module.exports = {
  addUnread,
  clearUnread,
  getUnread,
  getTotalUnread,
  clearAllUnread,
  getAllUnread,
  initRongCloudListener
};

